<?php

namespace App\Exports;

use App\Models\Asset;
use App\Models\Download;
use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class DeliveryExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;
    public $product;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query()
    {
        $this->product = Product::query()->find($this->request['id'] ?: 0);

        return Asset::query()
            ->where('contract_address', $this->product->contract_address)
            ->with(['user.address']);
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        $address = $value->user->address;

        return [
            $this->product->name,
            ' ' . $value->user->mobile,
            sprintf('[token_id] %s', $value->token_id),
            $value->created_at->toDateTimeString(),
            $value->source_type->description,
            $value->asset_status->description,
            $address ? $address->name : '用户未设置',
            $address ? $address->mobile : '用户未设置',
            $address ? $address->address : '用户未设置',
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            '商品名称',
            '持有人',
            '存证ID',
            '获取时间',
            '获取方式',
            '资产状态',
            '收货人姓名',
            '收货人手机号',
            '详细地址',
        ];
    }
}
